<template>
  <i-form
      ref="formRef"
      :model="formData"
      :rules="state.formRules"
      :label-width="100"
      label-position="right">
    <FormItem label="类别名称" prop="name">
      <Input v-model="formData.name" maxlength="20" show-word-limit/>
    </FormItem>
  </i-form>
</template>

<script setup>

import {getCurrentInstance, reactive, ref} from "vue";
import {FileTypeService} from "@/api/filetype";

const mode = ref('add');

const {proxy} = getCurrentInstance();

const formData = reactive({
  id: '',
  name: ''
})

const state = reactive({
  formRules: {
    name: [
      {required: true, message: '类别名称不能为空!'},
      {length: 20, message: '类别长度超出20!'}]
  }
})

const addFileTypeData = () => {
  proxy.$refs.formRef.validate(valid => {
    console.log(valid)
    if (!valid) {
      Promise.reject();
      return false;
    } else {
      if (mode.value === 'add') {
        post();
      } else {
        postDetail();
      }
    }
  })
}

const post = async () => {
  const {data} = await FileTypeService.AddFileType(formData);
  console.log(data)
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        // CommonServices.getMenus();
        window.location.reload()
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject()
      }
    })
  }
}

const postDetail = async () => {
  const {data} = await FileTypeService.ModifyFileType(formData);
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        window.location.reload()
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject()
      }
    })
  }
}

const getDetail = async (e) => {
  const param = {
    id: e.id
  }
  const {data} = await FileTypeService.GetFileTypeById(param);
  if (data.code === 200) {
    console.log(data.data)
    setFormData(data.data);
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject();
      }
    })
  }
}

const setFormData = (data) => {
  Object.assign(formData, data);
}

defineExpose({
  mode,
  addFileTypeData,
  getDetail
})

</script>

<style scoped>
</style>
